package com.hsy.swueasspider.utils

import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import android.view.ViewGroup
import android.webkit.CookieManager
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import com.hsy.swueasspider.TAG
import com.hsy.swueasspider.url.SwuEasUrl
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request

object SwuEasSpiderUtils {
    private var onPageVisibleCallback: MutableList<(String) -> Unit> = mutableListOf()

    fun addPageVisibleListener(listener: (String) -> Unit) {
        onPageVisibleCallback.add(listener)
    }

    val cookieManager: CookieManager = CookieManager.getInstance()

    // 可以用来请求数据的 cookie
    private var currentCookie = ""

    fun refreshCurrentCookie() {
        currentCookie = cookieManager.getCookie(SwuEasUrl.Base.EAS)
    }

    fun setCurrentCookie(cookie: String) {
        currentCookie = cookie
    }

    fun getCurrentCookie(context: Context): String {
        return if (isCookieUsable()) {
            currentCookie
        } else {
            Toast.makeText(context, "未连接到教务系统，请登录后重试", Toast.LENGTH_SHORT).show()
            currentCookie = ""
            currentCookie
        }
    }

    fun logOutEas(webView: WebView) {
        webView.loadUrl(SwuEasUrl.Base.LOG_OUT)
        cookieManager.removeAllCookies(null)
    }

    /** 检查 cookie 是否有效：给 EAS 发请求，返回 200 就是有效 */
    fun isCookieUsable(): Boolean {
        var isCookieUsable = false
        val easCookie = cookieManager.getCookie(SwuEasUrl.Base.EAS) ?: currentCookie
        if (easCookie.contains("JSESSIONID=")
            && easCookie.contains("TWFID=")
            && easCookie.contains("1=")
        ) {
            val client = OkHttpClient()
            val request = Request.Builder()
                .url(SwuEasUrl.Base.EAS)
                .addHeader("Cookie", easCookie)
                .build()
            runBlocking {
                withContext(Dispatchers.IO) {
                    try {
                        isCookieUsable = client.newCall(request).execute().isSuccessful
                    } catch (e: Exception) {
                        Log.e(TAG, "isCookieUsable -> $e")
                        isCookieUsable = false
                    }
                }
            }
        }
        return isCookieUsable
    }

    /** 初始化 webView */
    @SuppressLint("SetJavaScriptEnabled")
    fun initWebView(webView: WebView) {
        webView.settings.apply {
            userAgentString =
                "Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36 Edg/128.0.0.0"

            javaScriptEnabled = true
            javaScriptCanOpenWindowsAutomatically = true

            setSupportZoom(true)
            builtInZoomControls = true
            displayZoomControls = false

            cacheMode = WebSettings.LOAD_NO_CACHE
            domStorageEnabled = true
            databaseEnabled = true
            useWideViewPort = true

            loadWithOverviewMode = true
            useWideViewPort = true
        }

        webView.isHorizontalScrollBarEnabled = false
        webView.isVerticalScrollBarEnabled = false

        // 加载 jQuery 库，用来操作 dom 上的节点
        val script = "javascript:(function() { " +
                "var script = document.createElement('script');" +
                "script.src = 'file:///android_asset/jquery.min.js';" +
                "document.getElementsByTagName('head')[0].appendChild(script);" +
                "})()"
        webView.loadUrl(script)
    }

    fun initWebClient(webView: WebView) {
        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                Log.v(TAG, "-------------------- start --------------------")
                Log.v(TAG, request?.url.toString())
                Log.v(
                    TAG,
                    "请求方法 -> ${request?.method}\n" +
                            "请求头 -> ${request?.requestHeaders}"
                )
                Log.v(TAG, "-------------------- end --------------------")
                return super.shouldOverrideUrlLoading(view, request)
            }

            override fun onPageCommitVisible(view: WebView?, url: String?) {
                super.onPageCommitVisible(view, url)

                onPageVisibleCallback.forEach {
                    it.invoke(url ?: "")
                }
            }
        }
    }

    /** 销毁 webView，两个作用：
     * 1. 清空登录状态
     * 2. 防止内存泄漏
     * */
    fun destroyWebView(webView: WebView) {
        webView.apply {
            loadUrl("about:blank")
            parent?.let {
                (it as ViewGroup).removeView(webView)
            }
            stopLoading()
            settings.javaScriptEnabled = false
            clearHistory()
            clearCache(true)
            removeAllViewsInLayout()
            removeAllViews()
            webChromeClient = null
            destroy()
        }
    }
}